package com.yikes.srb.common.result;

import com.yikes.srb.common.enums.ResultCodeEnum;
import com.yikes.srb.common.enums.ResultCodeInterface;
import lombok.Data;

import java.io.Serializable;

/**
 * <p>
 *
 * </p>
 *
 * @Author: guanrong.yin
 * @Date: 2024/12/1 01:14
 */
@Data
public class Result<T> implements Serializable {

    private String code;

    private T data;

    private String msg;

    public static <T> Result<T> ok() {

        return result(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), null);
    }

    public static <T> Result<T> ok(T data) {
        Result<T> result = new Result<>();
        result.setCode(ResultCodeEnum.SUCCESS.getCode());
        result.setMsg(ResultCodeEnum.SUCCESS.getMsg());
        result.setData(data);
        return result;
    }

    public static <T> Result<T> fail() {
        return result(ResultCodeEnum.SYSTEM_EXECUTION_ERROR.getCode(), ResultCodeEnum.SYSTEM_EXECUTION_ERROR.getMsg(), null);
    }

    public static <T> Result<T> fail(String msg) {
        return result(ResultCodeEnum.SYSTEM_EXECUTION_ERROR.getCode(), msg, null);
    }

    public static <T> Result<T> judge(boolean status) {
        if (status) {
            return ok();
        } else {
            return fail();
        }
    }

    public static <T> Result<T> fail(ResultCodeInterface resultCode) {
        return result(resultCode.getCode(), resultCode.getMsg(), null);
    }

    public static <T> Result<T> fail(ResultCodeInterface resultCode, String msg) {
        return result(resultCode.getCode(), msg, null);
    }

    private static <T> Result<T> result(ResultCodeInterface resultCode, T data) {
        return result(resultCode.getCode(), resultCode.getMsg(), data);
    }

    private static <T> Result<T> result(String code, String msg, T data) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setData(data);
        result.setMsg(msg);
        return result;
    }

    /**
     * 返回分页数据
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result<T> build(T data) {

        return result(ResultCodeEnum.SUCCESS, data);
    }

    public static boolean isSuccess(Result<?> result) {
        if (result == null) {
            return false;
        }
        assert ResultCodeEnum.SUCCESS.getCode() != null;
        return ResultCodeEnum.SUCCESS.getCode().equals(result.getCode());
    }
}
